<template>
  <div>
    <div id="serverInfo">
      {{instance.name}}
      <span title="instance id">: {{instance.instanceId}}</span>
      <span v-if="instance.publicIp" title="public ip">: {{instance.publicIp}}</span>
      <span v-if="instance.privateIp" title="private ip">: {{instance.privateIp}}</span>
      <span title="instance type">: {{instance.instanceType}}</span>
      <span>: Font Size:
        <i class="fa fa-plus" title="Increase font size" v-on:click="fontSize('+')"></i>
        <i class="fa fa-minus" title="Decreate font size" v-on:click="fontSize('-')"></i>
      </span>
    </div>
    <div :id="'terminal' + tab" class="terminal"></div>
  </div>
</template>
<script>
  import * as Terminal from 'xterm';
  import {ipcRenderer} from 'electron';

  const Client = require('ssh2').Client;

  export default {
    name: 'sshConnection',
    data: function () {
      return {
        rendered: false,
        tab: null,
        connected: false,
        org: null,
        cloudService: null,
        instance: {}
      };
    },
    methods: {
      fontSize: function (dir) {
        let fontSize = parseInt($('#terminal' + this.tab + ' .terminal').css('font-size').replace(/px/, ''));
        if (dir === '+') {
          fontSize += 1;
        } else {
          fontSize -= 1;
        }
        $('#terminal' + this.tab + ' .terminal').css('font-size', fontSize + 'px');
        this.resizeIt();
      },
      resizeIt: function () {
        try {
          var term = this.term;
          var parentElementStyle = window.getComputedStyle(term.element.parentElement);
          var parentElementHeight = parseInt(parentElementStyle.getPropertyValue('height'));
          var parentElementWidth = Math.max(0, parseInt(parentElementStyle.getPropertyValue('width')));
          if (!$('#leftMenuExpanded').is(':visible')) {
            $('#terminal' + this.tab + ' .terminal').css('width', 'calc(100vw - 50px)');
            parentElementWidth += 200;
          } else {
            $('#terminal' + this.tab + ' .terminal').css('width', 'calc(100vw - 250px)');
          }
          var elementStyle = window.getComputedStyle(term.element);
          var elementPaddingVer = parseInt(elementStyle.getPropertyValue('padding-top')) + parseInt(elementStyle.getPropertyValue('padding-bottom'));
          var elementPaddingHor = parseInt(elementStyle.getPropertyValue('padding-right')) + parseInt(elementStyle.getPropertyValue('padding-left'));
          var availableHeight = parentElementHeight - elementPaddingVer;
          var availableWidth = parentElementWidth - elementPaddingHor;
          var subjectRow = term.rowContainer.firstElementChild;
          var contentBuffer = subjectRow.innerHTML;
          var characterHeight;
          var rows;
          var characterWidth;
          var cols;

          subjectRow.style.display = 'inline';
          subjectRow.innerHTML = 'W'; // Common character for measuring width, although on monospace
          characterWidth = subjectRow.getBoundingClientRect().width;
          subjectRow.style.display = ''; // Revert style before calculating height, since they differ.
          characterHeight = subjectRow.getBoundingClientRect().height;
          subjectRow.innerHTML = contentBuffer;

          rows = parseInt(availableHeight / characterHeight) - 3;
          cols = parseInt(availableWidth / characterWidth);
          term.resize(cols, rows);
          term.refresh(0, term.rows - 1);
        } catch (err) {
        }
      },
      ssh: async function (server) {
        const vue = this;
        let term = new Terminal({});
        term.open(document.getElementById('terminal' + this.tab), true);
        term._initialized = true;
        var conn = new Client();
        conn.on('ready', function () {
          conn.shell(function (err, stream) {
            if (err) {
              console.log(err);
            }
            stream.on('close', function () {
              // console.log('Stream :: close')
              conn.end();
            }).on('data', function (data) {
              // console.log('STDOUT: ' + data)
              term.write(unescape(encodeURIComponent(data)));
            }).stderr.on('data', function (data) {
              // console.log('STDERR: ' + data)
              term.write(unescape(encodeURIComponent(data)));
            });
            term.on('key', function (key, e) {
              stream.write(key);
              console.log('tagdfdafda:' + vue.tab);
            });
          });
        }).connect({
          host: server.host,
          port: server.port,
          username: server.userName,
          password: server.password
        });
        // This is hacky.   I can't figure out an event to know when to do this resize
        // so just going to wait a couple of seconds for now
        setTimeout(() => {
          this.resizeIt();
        }, 2000);
      }
    },
    beforeDestroy: function () {
      // term.destroy();
    },
    mounted: function () {
      ipcRenderer.on('resize', () => {
        this.resizeIt();
      });
      ipcRenderer.on('sshconnection.doSsh', async (e, data) => {
        console.log(data);
        if (this.rendered === false) {
          this.ssh(data.session);
          this.tab = data.tab;
        }
      });
    }
  };
</script>
<style>
  @import '../../assets/css/sshconnection.css';
</style>
